//
//  BuyViewController.m
//  HDYS
//
//  Created by qianfeng on 15-4-21.
//  Copyright (c) 2015年 kay. All rights reserved.
//

#import "BuyViewController.h"
#import "SearchViewController.h"
#import "MyCollectionViewCell.h"
#import "HeadCollectionViewCell.h"
#import "GoodsInfoViewController.h"
#import "Header.h"
#import "BuyDataModel.h"

#import "MainViewController.h"

#define COL_NUM 2

#define SECOND_CATE_WIDTH 80.0f
#define SECOND_CATE_SPACE 5


@interface BuyViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
{
    NSInteger secondBtnCount;
    
    //所有商品数据
    NSMutableArray *_totalDataArray;
    NSMutableArray *_userDataArray;
    
    NSMutableArray  *_tempArray;
}
//记录前一个被点击的分类按钮
@property (nonatomic, strong) UIButton *preBtn;
@property (nonatomic, strong) UIButton *secondPreBtn;

@property (nonatomic, strong) UIView *headView;

//数据源
@property (nonatomic, strong) NSMutableArray *buyDataArr;

@property (nonatomic, strong) UIScrollView *sv;
@property (nonatomic, strong) UIView *backView;

@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation BuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.buyDataArr = [NSMutableArray arrayWithCapacity:0];
    _totalDataArray = [NSMutableArray arrayWithCapacity:0];
    _userDataArray = [NSMutableArray arrayWithCapacity:0];
    _tempArray = [NSMutableArray arrayWithCapacity:0];
    
    [self loadData];
    [self createNaviItems];
}

-(void)loadData{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:INDEX_URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([json isKindOfClass:[NSDictionary class]]) {
            NSDictionary *d = [NSDictionary dictionaryWithDictionary:json];
            NSArray *array = [d objectForKey:@"gcdata"];
            for (NSDictionary *dic in array) {
                BuyDataModel *model = [[BuyDataModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.buyDataArr addObject:model];
            }
            
            //推荐
            NSArray *favDataArr = [d objectForKey:@"tdata"];
            for (NSDictionary *dic in favDataArr) {
                MainDataModel *model = [[MainDataModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_totalDataArray addObject:model];
            }
            //最新
            NSArray *latestDataArr = [d objectForKey:@"zdata"];
            for (NSDictionary *dic in latestDataArr) {
                MainDataModel *model = [[MainDataModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_totalDataArray addObject:model];
            }
            [_userDataArray addObjectsFromArray:_totalDataArray];
            [self createUI];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark - 创建ui
-(void)createNaviItems{
    UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    titleBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH - 100, 25);
    [titleBtn setTitle:@"搜索宝贝" forState:UIControlStateNormal];
    titleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    UIImage *image = [UIImage imageNamed:@"cancle_button"];
    UIImage *newImage = [image stretchableImageWithLeftCapWidth:5 topCapHeight:20];
    [titleBtn setBackgroundImage:newImage forState:UIControlStateNormal];
    [titleBtn addTarget:self action:@selector(titleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleBtn;
    
    UIButton *rigthBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rigthBtn.frame = CGRectMake(0, 0, 30, 30);
    [rigthBtn setBackgroundImage:[UIImage imageNamed:@"1003075"] forState:UIControlStateNormal];
    [rigthBtn addTarget:self action:@selector(buyCarBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rigthBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}


-(void)createUI{
    UIView *view = [self createHeadView];
    _headView = view;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 20) / COL_NUM, 260);
    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 90);
    
    UICollectionView *contentView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) collectionViewLayout:layout];

    contentView.backgroundColor = [UIColor whiteColor];
    contentView.delegate = self;
    contentView.dataSource = self;
    contentView.collectionViewLayout = layout;
    [self.view addSubview:contentView];
    self.collectionView = contentView;
    
    [contentView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"contentView"];
    [contentView registerClass:[HeadCollectionViewCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"contentHeadCell"];
}

//创建表头视图
- (UIView *)createHeadView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
    
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 4.5, SCREEN_WIDTH, 0.5)];
    lineView1.backgroundColor = [UIColor grayColor];
    [view addSubview:lineView1]; 
    
    CGFloat cateBtnW = (SCREEN_WIDTH - 20 - 20) / 5;
    for (int i = 0; i < self.buyDataArr.count+1; i++) {
        UIButton *cateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cateBtn.tag = 88 + i;
        cateBtn.frame = CGRectMake(10 + i * (cateBtnW + 5), 10, cateBtnW, 30);
        [cateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cateBtn addTarget:self action:@selector(cateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cateBtn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];

        if (i == 0) {
            [cateBtn setTitle:@"全部" forState:UIControlStateNormal];
            [cateBtn setBackgroundImage:[UIImage imageNamed:@"cancle_button"] forState:UIControlStateNormal];
            self.preBtn = cateBtn;
            [view addSubview:cateBtn];
            continue;
        }
        BuyDataModel *model = self.buyDataArr[i-1];
        [cateBtn setTitle:model.cname forState:UIControlStateNormal];
        [view addSubview:cateBtn];
    }
    UIButton *btn = (UIButton *)[view viewWithTag:88];
    
    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, btn.frame.origin.y + btn.frame.size.height + 5, SCREEN_WIDTH, 0.5)];
    lineView2.backgroundColor = [UIColor grayColor];
    [view addSubview:lineView2];
    
    
    for (BuyDataModel *model in self.buyDataArr) {
        [model.zclass count];
        NSArray *array = model.zclass;
        secondBtnCount += array.count;
    }
    UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, lineView2.frame.origin.y + lineView2.frame.size.height, SCREEN_WIDTH, 40)];
    sv.contentSize = CGSizeMake(20 + secondBtnCount * (SECOND_CATE_WIDTH + SECOND_CATE_SPACE), 40);
    self.sv = sv;
    
    [self loadSecondCateWithIndex:-1];
    
    [view addSubview:sv];

    //线条
    UIView *lineView3 = [[UIView alloc] initWithFrame:CGRectMake(sv.frame.origin.x, sv.frame.origin.y + sv.frame.size.height, SCREEN_WIDTH, 0.5)];
    lineView3.backgroundColor = [UIColor grayColor];
    [view addSubview:lineView3];
    
    return view;
}


- (void)loadSecondCateWithIndex:(NSInteger)index {
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.sv.contentSize.width, self.sv.contentSize.height)];
    self.backView = backView;
    backView.backgroundColor = [UIColor whiteColor];
    [self.sv addSubview:backView];
    
    //全部
    if (index == -1) {
        self.sv.contentSize = CGSizeMake(20 + secondBtnCount * (SECOND_CATE_WIDTH + SECOND_CATE_SPACE), 40);
        backView.frame = CGRectMake(0, 0, self.sv.contentSize.width, self.sv.contentSize.height);
        int i = 0;
        for (BuyDataModel *model in self.buyDataArr) {
            NSArray *array = model.zclass;
            for (NSDictionary *d in array) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.tag = 190 + i;
                btn.frame = CGRectMake(SECOND_CATE_SPACE * 2 + i * (SECOND_CATE_WIDTH + SECOND_CATE_SPACE), SECOND_CATE_SPACE, SECOND_CATE_WIDTH, self.sv.frame.size.height - SECOND_CATE_SPACE * 2);
                [btn setTitle:[d objectForKey:@"cname"] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:14];
                [btn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(secondCateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                [backView addSubview:btn];
                i++;
            }
        }
    } else { //分类
        self.sv.contentSize = CGSizeMake(SCREEN_WIDTH + 5, backView.frame.size.height);
        BuyDataModel *model = self.buyDataArr[index];
        NSArray *array = model.zclass;
        for (int i = 0; i < array.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.tag = 700 + i + index * 5;
            btn.frame = CGRectMake(2 * SECOND_CATE_SPACE + (SECOND_CATE_WIDTH + SECOND_CATE_SPACE) * i, SECOND_CATE_SPACE, SECOND_CATE_WIDTH, backView.frame.size.height - 10);
            [btn setTitle:[array[i] objectForKey:@"cname"] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(secondCateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [backView addSubview:btn];
        }
    }
}

#pragma mark - 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
        return _userDataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"contentView";
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell configUIWithModel:_userDataArray[indexPath.row]];
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 5, 15, 5);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10.0f;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"contentHeadCell" forIndexPath:indexPath];
    [headView addSubview:_headView];
    return headView;
}


#pragma mark - UKWaterFlowLayoutDelegate代理
- (NSInteger)numberOfColumns {
    return COL_NUM;
}



/**
 *  选中某个cell
 */
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    GoodsInfoViewController *goodsVC = [[GoodsInfoViewController alloc] init];
    goodsVC.hidesBottomBarWhenPushed = YES;
    MainDataModel *model = _userDataArray[indexPath.row];
    goodsVC.model = model;
    [self presentViewController:goodsVC animated:YES completion:nil];
}


/**
 *  给不同的cell设置不同size
 */
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    return CGSizeMake((SCREEN_WIDTH - 20) / COL_NUM, 260);
//}


#pragma mark - 点击事件
//点击分类按钮
-(void)cateBtnClick:(UIButton *)btn{
    [self.preBtn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"cancle_button@2x"] forState:UIControlStateNormal];
    self.preBtn = btn;
    
    [self.backView removeFromSuperview];
    self.backView = nil;
    
    // 改变次级分类按钮的内容
    NSInteger index = btn.tag - 88 - 1;
    [self loadSecondCateWithIndex:index];
    
    [_userDataArray removeAllObjects];
    if (index == -1) {
        [_userDataArray addObjectsFromArray:_totalDataArray];
        [self.collectionView reloadData];
    } else {
        BuyDataModel *model = self.buyDataArr[index];
        NSArray *a = model.zclass;
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *d in a) {
            [array addObject:[d objectForKey:@"id"]];
        }
        for (NSString *str in array) {
            for (BuyDataModel *goodModel in _totalDataArray) {
                if ([goodModel.classid isEqualToString:str]) {
                    [_userDataArray addObject:goodModel];
                }
            }
        }
        [self.collectionView reloadData];
    }
}

-(void)secondCateBtnClick:(UIButton *)btn{
    NSLog(@"secondCateBtn = %ld",btn.tag);
    [self.secondPreBtn setBackgroundImage:[UIImage imageNamed:@"bg"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"cancle_button@2x"] forState:UIControlStateNormal];
    self.secondPreBtn = btn;

    
}

#pragma mark - 购物车按钮
-(void)buyCarBtnClick{
    self.tabBarController.selectedIndex = 2;
}


/**
 *  进入搜索页面
 */
#pragma mark - 搜索
-(void)titleBtnClick{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    searchVC.block = ^void (BOOL isShow){
        [self.navigationController setNavigationBarHidden:isShow animated:YES];
    };
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
